package com.css.crm.dbunit;

import java.sql.Connection;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.filter.IColumnFilter;
import org.dbunit.ext.oracle.Oracle10DataTypeFactory;
import org.w3c.dom.NamedNodeMap;

import com.css.db.util.DBConfigUtil;

/**
 * db unit related configuration
 * 
 * @author Administrator
 * 
 */
public class DbUnit {

	protected IDatabaseConnection connection;
	public final static String TEST_DB_SCHEMA = "SYSVIP";
	private String configPK = null;

	public IDatabaseConnection getConnection() throws Exception {
		if (connection == null) {
			connection = new DatabaseConnection(getDBConnection(), TEST_DB_SCHEMA);
		}

		// if table have no PK, then need to config use which field as pk
		if (configPK != null) {
			connection.getConfig().setProperty(DatabaseConfig.PROPERTY_PRIMARY_KEY_FILTER, new MyPrimaryKeyFilter(configPK));
		}

		connection.getConfig().setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new Oracle10DataTypeFactory());

		return connection;
	}

	/**
	 * use for set table primary key when table structure have none
	 * 
	 * @author Administrator
	 */
	class MyPrimaryKeyFilter implements IColumnFilter {

		private String pseudoKey = null;

		MyPrimaryKeyFilter(String pseudoKey) {
			this.pseudoKey = pseudoKey;
		}

		public boolean accept(String tableName, Column column) {
			return column.getColumnName().equalsIgnoreCase(pseudoKey);
		}
	}

	public Connection getDBConnection() throws Exception {
		NamedNodeMap configMap = DBConfigUtil.readDbConfig();
		String jndiName = configMap.getNamedItem("name").getNodeValue();
		Context initContext = new InitialContext();
		DataSource ds = (DataSource) initContext.lookup("java:/comp/env/" + jndiName);
		Connection conn = ds.getConnection();
		return conn;
	}

	public String getConfigPK() {
		return configPK;
	}

	public void setConfigPK(String configPK) {
		this.configPK = configPK;
	}
}
